import VueI18n from 'vue-i18n';
import Cookies from 'js-cookie';
import dragVerify from 'vue-drag-verify';
import {
  fetchLogin,
  fetchSendValidateCode,
  fetchUpdatePwd,
  fetchGetIndustry,
  fetchHasUser,
  fetchCheckValidate,
  fetchRegsiterAccount,
  fetchSearchUserCode,
  fetchCreateState,
  fetchAppCreateUser,
  fetchSetQRcode,
  fetchQRlogin,
  fetchState,
  checkingUser,
  phoneBlur,
  getLoginDsfConfig,
} from '../js/login';
// import {
//   Message, Notification
// } from 'element-ui'
import {
  loadCache,
  generateQRcode,
  dingTalkLogin,
  weChatLogin,
  getDingTalkUserInfo,
  getWeChatUserInfo,
} from '../js/loginUtil.js';
import {
  getParam, decipherStr,
} from '../js/common.js';
import loginLogo from '../assets/logo.png';
import loginBgimg from '../assets/bg/plus_bg_01_h.jpg';
import loginBgimgblur from '../assets/bg/plus_bg_01_s.jpg';
import LOGIN_CONFIGPZ from './login_config.js';
import spe from '../assets/lang/speNationalList';
import cn from '../assets/China.png';
import en from '../assets/English.png';
import loginErrMsg from '../js/loginErrMsg';

const i18n = new VueI18n({
  locale: 'zh_CN', // 语言标识
  messages: {
    zh_CN: require('./../assets/lang/zh'), // 中文语言包
    en: require('./../assets/lang/en'), // 英文语言包
  },
});

export default {
  name: 'Login',
  components: {
    dragVerify,
  },
  i18n,
  data() {
    // 登录验证密码还是验证码
    const validatePass = (rule, value, callback) => {
      if (!this.isNoteLogin) {
        if (!this.loginFrom.pwd) {
          return callback(new Error('请输入密码'));
        }
        callback();
      } else {
        if (!this.loginFrom.validateCode) {
          return callback(new Error('请输入短信验证码'));
        }
        callback();
      }
    };
    // 验证短信验证码
    const validateCode = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入短信验证码'));
      }
      callback();
    };
    // 验证手机号
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        // return callback(new Error('请输入手机号'))
        return callback(new Error('请输入账号'));
      }
      // const regPhone = /^(((13[0-9]{1})|(15[0-9]{1})|(17[0-9]{1})|(18[0-9]{1}))+\d{8})$/
      // const regPhone = /^1[345678]\d{9}$/;

      // if (!regPhone.button(value)) {
      //   return callback(new Error('手机号格式不正确，需重新输入'))
      // } else {
      //   callback()
      // }
      callback();
    };
    // 验证两次密码是否一致
    const validatePass2 = (rule, value, callback) => {
      if (this.findPwdFrom.oldPwd !== this.findPwdFrom.newPwd) {
        callback(new Error('两次输入密码不一致'));
      } else {
        callback();
      }
    };
    // 验证密码
    const validateFindPwdPass = (rule, value, callback) => {
      const reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/;
      if (!value) {
        callback(new Error('请输入密码!'));
      } else if (!reg.test(value)) {
        callback(new Error('密码格式不正确，请输入6位以上字母+数字'));
      } else {
        callback();
      }
    };
    // 验证邮箱
    const validateEmail = (rule, value, callback) => {
      const reg = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/;
      if (!value) {
        callback(new Error('请输入邮箱!'));
      } else if (!reg.test(value)) {
        callback(new Error('邮箱格式不正确'));
      } else {
        callback();
      }
    };
    // 验证企业
    const validateEnterpriseName = (rule, value, callback) => {
      const reg = /^[\u4E00-\u9FA5]+$/;
      if (!value) {
        callback(new Error('请输入企业!'));
      } else if (!reg.test(value)) {
        callback(new Error('企业名称格式不正确'));
      } else {
        callback();
      }
    };
    // 验证姓名
    const validateName = (rule, value, callback) => {
      const reg = /^[\u4E00-\u9FA5A-Za-z]+$/;
      if (!value) {
        callback(new Error('请输入真实姓名!'));
      } else if (!reg.test(value)) {
        callback(new Error('真实姓名格式不正确'));
      } else {
        callback();
      }
    };
    // 根据页面变量替换默认值
    const LOGIN_CONFIG = window.LOGIN_CONFIG || LOGIN_CONFIGPZ;

    return {
      cn,
      en,
      LOGIN_CONFIG,
      LOGIN_CONFIG_LOGO: LOGIN_CONFIG.LOGO || loginLogo,
      LOGIN_CONFIG_BGIMG: LOGIN_CONFIG.BGIMG || loginBgimg,
      LOGIN_CONFIG_BGIMGBLUR: LOGIN_CONFIG.BGIMGBLUR || loginBgimgblur,
      LOGIN_CONFIG_THEMECOLOR: LOGIN_CONFIG.THEMECOLOR || '#3173cc',
      handlerIcon: 'el-icon-d-arrow-right1',
      successIcon: 'el-icon-circle-check',
      background: '#F5F5F5',
      progressBarBg: '#BBEA94',
      completedBg: '#BBEA94',
      handlerBg: '#fff',
      text: '请将滑块拖动到右侧',
      successText: '验证通过',
      width: 338,
      height: 32,
      textSize: '12px',
      isCircle: 'true',
      dragVerifyinput: false,
      dragVerifycode: '',

      typeText: '', // 快捷登录
      appInfo: {},
      isLoaded: true, // 是否加载完成
      registerType: '', // 注册类型
      login: true,
      showMessageFlag: false, // 表单不显示错误提示
      form: {},
      remberStatus: true, // 是否记住登录状态
      level: 0, // 密码强度
      pwd: '', // 登录用密码
      validateCode: '', // 登录用验证码
      login_dsf_config: {
        JE_SYS_QUICKLOGIN: '1',
        JE_SYS_DDQUICKLOGIN: '1',
        JE_SYS_WXQUICKLOGIN: '1',
        JE_SYS_QQQUICKLOGIN: '1',
      }, // 第三方登录的配置信息
      LOGIN_QQ_APPID: '', // QQ appid
      LOGIN_QQ_APPKEY: '', // QQ appkey
      LOGIN_QQ_REDIRECT_URI: '', // QQ回调地址
      LOGIN_DINGTALK_APPID: '', // 钉钉 appid
      LOGIN_DINGTALK_APP_SECRET: '', // 钉钉 appsercet
      LOGIN_DINGTALK_REDIRECT_URI: '', // 钉钉回调地址
      LOGIN_WX_APPID: '', // 微信appi
      LOGIN_WX_SECRET: '', // 微信secret
      LOGIN_WX_REDIRECT_URI: '', // 微信回调地址
      loginFrom: {
        phone: '',
        pwd: '',
        validateCode: '',
      }, // 登录
      rulesLoginFrom: {
        phone: [{
          validator: validatePhone,
          trigger: 'blur',
        }],
        pwd: [{
          validator: validatePass,
          trigger: 'blur',
        }],
        validateCode: [{
          validator: validatePass,
          trigger: 'blur',
        }],
      },
      loginFormErrorMsg: '',
      loginType: true, // 登录类型
      isNoteLogin: false, // 密码输入方式 /是否验证码
      sendAuthCode: true, // 验证码
      auth_time: 0, // 验证码时间
      findPwd: false, // 找回密码
      findPwdFrom1: {}, // 找回密码
      rulesfindPwdFrom1: {
        phone: [{
          validator: validatePhone,
          trigger: 'blur',
        }],
        validateCode: [{
          validator: validateCode,
          trigger: 'blur',
        }],
      },
      showSelectType: true, // 判断是选择企业null || 1 ；还是选择部门0
      findPwdForm1ErrorMsg: '', // 错误是
      findPwdFrom: {}, // 找回密码
      rulesfindPwdFrom: {
        oldPwd: [{
          validator: validateFindPwdPass,
          trigger: 'blur',
        }],
        newPwd: [{
          validator: validatePass2,
          trigger: 'blur',
        }],
      },
      findPwdFormErrorMsg: '', // 错误
      findPwdState: '1', // 找回密码
      updateSuccess: false, // 密码修改成功
      showQrCode: false, // 显示二维码
      register: false, // 注册
      isShowRegister: '1', // 注册步骤
      registerFrom: {},
      rulesRegisterFrom: {
        phone: [{
          validator: validatePhone,
          trigger: 'blur',
        }],
        validateCode: [{
          validator: validateCode,
          trigger: 'blur',
        }],
        pwd: [{
          validator: validateFindPwdPass,
          trigger: 'blur',
        }],
      },
      registerFromErrorMsg: '',
      registerFrom3: {},
      registerForm3ErrorMsg: '',
      rulesRegisterFrom3: {
        enterpriseName: [{
          trigger: 'blur',
          validator: validateEnterpriseName,
        }],
        name: [{
          validator: validateName,
          trigger: 'blur',
        }],
        email: [{
          validator: validateEmail,
          trigger: 'blur',
        }],
        industry: [{
          required: true,
          message: '请选择行业',
          trigger: 'change',
        }],
      },
      registerSuccess: {}, // 注册成功信息
      bgImgUrlIn: '', // 背景图片
      bgImgUrlOut: '', // 背景图片
      showImg: false, // 背景图片
      filterBlur: 20, // 背景图片效果
      showCompany: false, // 显示公司
      companyList: [], // 公司列表
      industryList: [], // 行业列表
      dsfState: '', // 第三方登录的state
      placeHoldertext: '',
      lang: 'zh_CN',
      isSubmiting: false, // 忘记密码提交状态
      // 新增轮播
      slideList: [
        { src: require('../assets/new-slide1.png') },
        { src: require('../assets/new-slide2.png') },
      ],
      SHOWI18N: LOGIN_CONFIG.SHOWI18N,
      I18NLIST: LOGIN_CONFIG.I18NLIST,
      casParams: {
        client_id: '',
        response_type: '',
        redirect_uri: '',
      }, // 单点登录 参数
    };
  },
  watch: {
    loginFrom: {
      deep: true,
      handler() {
        // this.pwd = ''
        this.validateCode = '';
      },
    },
  },
  created() {
    // IE9  兼容window.btoa/atob方法
    if (!window.btoa) window.btoa = $.base64.btoa;
    if (!window.atob) window.atob = $.base64.atob;

    const that = this;
    // 初始化平台关于第三方登录的配置信息
    that.getDsfConfig();
    if (!Cookies.get('je-local-lang') || Cookies.get('je-local-lang') !== 'en') {
      Cookies.set('je-local-lang', 'zh_CN', {
        expires: 36500,
      });
      this.$i18n.locale = 'zh_CN';
      this.lang = 'zh_CN';
    } else {
      this.$i18n.locale = Cookies.get('je-local-lang');
      this.lang = Cookies.get('je-local-lang');
    }
    // if (Cookies.get('je-local-lang')) {
    //   this.$i18n.locale = Cookies.get('je-local-lang');
    //   this.lang = Cookies.get('je-local-lang');
    // } else {
    //   this.lang = this.$i18n.locale;
    //   Cookies.set('je-local-lang', this.$i18n.locale);
    // }
  },
  mounted() {
    if (getParam(window.location.href, 'type') === 'register') {
      this.goRegister('PC');
    }
    if (Cookies.get('phone') && Cookies.get('password')) {
      this.loginFrom.phone = Cookies.get('phone');
      this.pwd = this.loginFrom.pwd = decipherStr(Cookies.get('password'));
    }
    // 回车登录
    document.onkeydown = (event) => {
      const e = event || window.event;
      if (e && e.keyCode === 13) {
        if (this.loginType && this.login) {
          this.loginSubmit('loginFrom');
        }
      }
    };
    loadCache();

    if (getParam(window.location.href, 'client_id')) {
      this.casParams.client_id = getParam(window.location.href, 'client_id');
    }
    if (getParam(window.location.href, 'response_type')) {
      this.casParams.response_type = getParam(window.location.href, 'response_type');
    }
    if (getParam(window.location.href, 'redirect_uri')) {
      this.casParams.redirect_uri = getParam(window.location.href, 'redirect_uri');
    }
  },
  methods: {
    // 初始化平台关于第三方登录的配置信息
    async getDsfConfig() {
      const that = this;
      const res = await getLoginDsfConfig();
      if (res.success && res.obj) {
        that.login_dsf_config = res.obj;
        that.LOGIN_QQ_APPID = res.obj.QQ_LOGIN_APPID || ''; // QQ appid
        that.LOGIN_QQ_APPKEY = res.obj.QQ_LOGIN_APPKEY || ''; // QQ appkey
        that.LOGIN_QQ_REDIRECT_URI = encodeURIComponent(`${res.obj.QQ_LOGIN_APPURL}/login.html`) || ''; // QQ回调地址
        that.LOGIN_DINGTALK_APPID = res.obj.DINGTALK_APPID || ''; // 钉钉 appid
        that.LOGIN_DINGTALK_APP_SECRET = res.obj.DINGTALK_APPKEY || ''; // 钉钉 appsercet
        that.LOGIN_DINGTALK_REDIRECT_URI = `${res.obj.DINGTALK_REDIRECT_URI}/login.html` || ''; // 钉钉回调地址
        that.LOGIN_WX_APPID = res.obj.WX_LOGIN_APPID || ''; // 微信appi
        that.LOGIN_WX_SECRET = res.obj.WX_LOGIN_APPSECRET || '';// 微信secret
        that.LOGIN_WX_REDIRECT_URI = `${res.obj.WX_LOGIN_APPURL}/login.html` || ''; // 微信回调地址

        const state = getParam(window.location.href, 'state');
        if (state) {
          const app = state.substring(0, 2);
          this.isLoaded = false;
          if (app === 'DT') {
            this.getAppUserInfo('dt');
          } else if (app === 'WX') {
            this.getAppUserInfo('wx');
          } else if (app === 'QQ') {
            const { href } = window.location;
            const token = href.split('#')[1].split('&')[0].split('=')[1];
            function callback(data) {
              console.log(data);
            }
            $.ajax({
              type: 'get',
              async: false,
              data: { access_token: token, unionid: '1' },
              url: 'https://graph.qq.com/oauth2.0/me',
              dataType: 'jsonp',
              jsonp: 'callback', // 传递给请求处理程序或页面的，用以获得jsonp回调函数名的参数名(一般默认为:callback)
              jsonpCallback: 'callback', // 自定义的jsonp回调函数名称，默认为jQuery自动生成的随机函数名，也可以写"?"，jQuery会自动为你处理数据
              success(json) {
                that.sendLogin('dsf', { code: json.unionid, state });
              },
              error(e) {
                alert('登录失败');
                console.log(e);
              },
            });
          }
        }
      }
    },
    changeLang(item) {
      this.lang = item.value;
      this.$i18n.locale = item.value;
      Cookies.set('je-local-lang', item.value);
      // 切换中引文时，清除错误信息
      this.loginFormErrorMsg = '';
      this.findPwdForm1ErrorMsg = '';
      this.findPwdFormErrorMsg = '';
      this.registerFromErrorMsg = '';
      this.registerForm3ErrorMsg = '';
    },
    // 登录
    loginSubmit(formName) {
      if (!this.isNoteLogin) {
        if (!this.loginFrom.pwd) {
          this.loginFrom.pwd = this.pwd;
        }
      }
      if (this.dragVerifyinput) {
        const { isPassing } = this.$refs.Verify;
        if (!isPassing) {
          this[this.formErrorMsg('loginFrom')] = '请先滑动解锁';
          return;
        }
      }
      this.$refs[formName].validate(async (valid, fields) => {
        if (valid) {
          if (this.isNoteLogin) {
            // 校验验证码
            const validateCodeRes = await this.validatePhoneCode(
              this.loginFrom.phone,
              'LOGIN',
              this.loginFrom.validateCode,
            );
            if (!validateCodeRes.success) {
              // this.messageTip(validateCodeRes.msg || validateCodeRes.message)
              this[this.formErrorMsg('loginFrom')] = validateCodeRes.msg || validateCodeRes.message;
              return false;
            }
            /* this.directLogin(this.loginFrom.phone, 'code', {
              j_code: this.loginFrom.validateCode
            }) */
            this.sendLogin('code', {
              j_username: this.loginFrom.phone,
              j_code: this.loginFrom.validateCode,
              state: '',
            });
            this.$nextTick(() => {
              this.clearCookie('__jeplus_info__');
              this.clearCookie('__qc_wId');
              this.clearCookie('authorization');// 删除cookie值
              this.clearCookie('pgv_pvid');
              this.clearCookie('phone');
            });
          } else {
            /* this.directLogin(this.loginFrom.phone, 'pwd', {
              password: this.loginFrom.pwd || this.pwd
            }) */
            this.sendLogin('pwd', {
              j_username: this.loginFrom.phone,
              j_password: this.loginFrom.pwd || this.pwd,
              j_code: this.dragVerifycode,
            });
            this.$nextTick(() => {
              this.clearCookie('__jeplus_info__');
              this.clearCookie('__qc_wId');
              this.clearCookie('authorization');// 删除cookie值
              this.clearCookie('pgv_pvid');
              this.clearCookie('phone');
            });
          }
        } else {
          this.formError('loginFormErrorMsg', fields);
        }
      });
    },
    clearCookie(name) {
      this.setCookie(name, '', -1);
    },
    setCookie(cname, cvalue, exdays) {
      const d = new Date();
      d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
      const expires = `expires=${d.toUTCString()}`;
      document.cookie = `${cname}=${cvalue}; ${expires}; path=/`;// path=/是根路径
    },
    // 找回密码第一步
    findPwdFrom1Next(formName) {
      this.$refs[formName].validate(async (valid, fields) => {
        if (valid) {
          // 校验验证码
          const validateCodeRes = await this.validatePhoneCode(
            this.findPwdFrom1.phone,
            'ZH',
            this.findPwdFrom1.validateCode,
          );
          this.findPwdState = '3';
          // if (validateCodeRes.success) {
          //   const listRes = await this.getUserList(this.findPwdFrom1.phone)
          //   if (listRes.success) {
          //     const companyList = listRes.obj
          //     if (companyList.length > 0 && companyList.length <= 1) {
          //       this.selComapnyPwd(companyList[0])
          //     } else {
          //       this.findPwdState = '2'
          //     }
          //   }
          // } else {
          //   // this.messageTip(validateCodeRes.msg || validateCodeRes.message)
          //   this[this.formErrorMsg('findPwdFrom1')] = validateCodeRes.msg || validateCodeRes.message
          // }
        } else {
          this.formError('findPwdForm1ErrorMsg', fields);
        }
      });
    },
    // 找回密码第二步选择公司
    selComapnyPwd(item) {
      this.findPwdFrom1.deptId = item.DEPTID || 'default';
      this.findPwdState = '3';
    },
    // 找回密码第三步提交
    findPwdLogin(formName) {
      this.$refs[formName].validate(async (valid, fields) => {
        if (valid) {
          this.isSubmiting = true;
          const params = {
            j_username: this.findPwdFrom1.phone,
            j_password: this.findPwdFrom.oldPwd,
            code: this.findPwdFrom1.validateCode,
            type: 'PHONE',
            j_dept: this.findPwdFrom1.deptId || '',
          };
          const res = await fetchUpdatePwd(params);
          if (res.success) {
            this.isSubmiting = false;
            this.updateSuccess = true;
            this.findPwd = false;
          } else {
            this.isSubmiting = false;
            // this.messageTip('设置密码失败')
            this[this.formErrorMsg('findPwdFrom')] = '设置密码失败';
          }
        } else {
          this.formError('findPwdFormErrorMsg', fields);
        }
      });
    },
    // 注册第一步骤
    registerLoginSubmit(formName) {
      this.$refs[formName].validate(async (valid, fields) => {
        if (valid) {
          // 校验验证码
          const validateCodeRes = await this.validatePhoneCode(
            this.registerFrom.phone,
            'ZC',
            this.registerFrom.validateCode,
          );
          if (validateCodeRes.success) {
            // 检测用户是否存在
            const res = await fetchHasUser({
              email: this.registerFrom.phone,
              type: 'PHONE',
            });
            if (res.success) {
              await this.getUserList(this.registerFrom.phone);
              this.isShowRegister = '2';
              if (this.appInfo.code) {
                this.appInfo.phonemumber = this.registerFrom.phone;
              }
            } else {
              this.isShowRegister = '3';
            }
            this.getIndustry();
          } else {
            // this.messageTip(validateCodeRes.msg || validateCodeRes.message)
            this[this.formErrorMsg('registerFrom')] = validateCodeRes.msg || validateCodeRes.message;
          }
        } else {
          this.formError('registerFromErrorMsg', fields);
        }
      });
    },
    // 注册返回
    registerBack() {
      if (this.companyList.length > 0) {
        this.isShowRegister = '2';
      } else {
        this.isShowRegister = '1';
      }
    },
    // 注册企业
    registerEnterPrise(formName) {
      this.$refs[formName].validate(async (valid, fields) => {
        if (valid) {
          let tradeName = '';
          for (const item of this.industryList) {
            if (this.registerFrom3.industry === item.value) {
              tradeName = item.text;
              break;
            }
          }
          let joinCompanyRes = {};
          const params = {
            email: this.registerFrom.phone,
            companyname: this.registerFrom3.enterpriseName,
            companyemail: this.registerFrom3.email,
            username: this.registerFrom3.name,
            tradeName,
            tradeCode: this.registerFrom3.industry,
            password: this.registerFrom.pwd,
            username_zh: this.registerFrom.phone,
            phone: this.registerFrom.phone,
          };
          if (this.registerType === 'PC') {
            joinCompanyRes = await fetchRegsiterAccount(
              Object.assign(params, {
                type: 'PHONE',
                code: this.registerFrom.validateCode,
              }),
            );
          } else {
            joinCompanyRes = await fetchAppCreateUser(
              Object.assign(params, {
                type: this.registerType,
                openId: this.appInfo.openId,
                unionId: this.appInfo.openId,
                access_token: this.appInfo.accessToken,
              }),
            );
          }
          if (joinCompanyRes.success) {
            const registerRes = {}; let
              token = '';
            if (this.registerType === 'PC') {
              token = joinCompanyRes.obj;
            } else {
              token = joinCompanyRes.obj.data;
            }
            /* this.registerSuccess = {
              name: registerRes.username,
              enterpriseName: registerRes.companyname,
              companyId: registerRes.companyCode,
              userId: registerRes.userCode,
              pwd: this.registerFrom.pwd,
              phone: this.registerFrom.phone,
              DEPTID: registerRes.DEPTID
            } */
            // this.isShowRegister = '4'
            Cookies.set('phone', this.registerFrom.phone, {
              expires: 30,
            });
            Cookies.set('authorization', token, {
              expires: 365,
            });
            setTimeout(() => location.href = '/index.html', 1000);
          } else {
            // this.isShowRegister = '4'
            // this.messageTip(joinCompanyRes.msg || joinCompanyRes.message)
            this[this.formErrorMsg('registerFrom3')] = joinCompanyRes.msg || joinCompanyRes.message;
          }
        } else {
          this.formError('registerForm3ErrorMsg', fields);
        }
      });
    },
    // 处理登录类型占位符
    placeHolder(account) {
      let placeHoldertext = '';
      account.filter((accountitem) => {
        if (accountitem.enable) {
          placeHoldertext += `${accountitem.text}/`;
        }
      });
      return placeHoldertext.substr(0, placeHoldertext.length - 1);
    },
    // 获取验证码
    async getValidateCode(phone, type, formName) {
      let message = '';
      if (!phone) {
        message = '请输入手机号/账户';
      } else {
        const regPhone = /^(((13[0-9]{1})|(14[0-9]{1})|(15[0-9]{1})|(16[0-9]{1})|(17[0-9]{1})|(18[0-9]{1})|(19[0-9]{1}))+\d{8})$/;
        if (!regPhone.test(phone)) {
          message = '手机号格式不正确，需重新输入';
        }
      }
      this[this.formErrorMsg(formName)] = message;
      if (this.sendAuthCode && !message) {
        const res = await fetchSendValidateCode({
          email: phone,
          type: 'PHONE',
          cz: type,
        });
        if (res.success) {
          this.sendAuthCode = false;
          this.auth_time = 59;
          // this.messageTip('验证码发送成功', 'success')
          const auth_timetimer = setInterval(() => {
            this.auth_time--;
            if (this.auth_time <= 0) {
              this.sendAuthCode = true;
              clearInterval(auth_timetimer);
            }
          }, 1000);
        } else {
          this[this.formErrorMsg(formName)] = res.msg || res.message;
          // this.messageTip(res.msg || res.message)
        }
      }
    },
    // 验证验证码
    validatePhoneCode(phone, type, code) {
      return fetchCheckValidate({
        email: phone,
        type: 'PHONE',
        cz: type,
        code,
      });
    },
    // 验证表单字段
    customValidateForm(formName, Booleans) {
      const fieldsStr = this.formErrorMsg(formName);
      if (Booleans) {
        // const regPhone = /^(((13[0-9]{1})|(15[0-9]{1})|(16[0-9]{1})||(17[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
        const { phone } = this.loginFrom;
        // if (!regPhone.button(phone)) {
        if (!phone.trim()) {
          // let message = '手机号格式不正确，需重新输入';
          const message = '登录账号不能为空，请重新输入';
          this[this.formErrorMsg(formName)] = message;
        } else {
          // 如果是手机号失去焦点  请求后台   处理滑动解锁是否展示
          this.isShowDragVerify(phone);
        }
      } else {
        this.$refs[formName].validate((valid, fields) => {
          if (valid) {
            this[fieldsStr] = '';
          } else {
            for (const prop in fields) {
              if (this[fieldsStr] !== fields[prop][0].message) {
                this[fieldsStr] = '';
              }
              break;
            }
          }
        });
      }
    },
    // 手机号失去焦点，请求后台接口
    async isShowDragVerify(phone) {
      // 请求后台
      // 规则说明：
      // 1、密码登录，密码错误2次后，显示 滑动验证区域。
      // 2、滑动操作后，允许点击登录按钮。
      // 注：1、输入手机号后，失去焦点，需要调用后台方法，获取该手机号登录密码错误次数。
      //  2、显示 滑动验证时，需要调用后台接口，获取验证码。
      //  3、点击登录时，需要后台校验 滑动验证 是否通过。
      //  4、密码错误5次，禁用账号

      // const isPassing = this.$refs.Verify.isPassing;
      const phoneafterBlur = await phoneBlur({ j_username: phone });
      if (!phoneafterBlur.success) {
        this.dragVerifyinput = true;
        this.dragVerifycode = phoneafterBlur.obj;
      }
    },
    // 对应表单的错误提示字段
    formErrorMsg(formName) {
      let errorMsg;
      switch (formName) {
        case 'loginFrom':
          errorMsg = 'loginFormErrorMsg';
          break;
        case 'findPwdFrom1':
          errorMsg = 'findPwdForm1ErrorMsg';
          break;
        case 'findPwdFrom':
          errorMsg = 'findPwdFormErrorMsg';
          break;
        case 'registerFrom':
          errorMsg = 'registerFromErrorMsg';
          break;
        case 'registerFrom3':
          errorMsg = 'registerForm3ErrorMsg';
          break;
      }
      return errorMsg;
    },
    // 表单提示
    formError(label, fields) {
      for (const prop in fields) {
        this[label] = fields[prop][0].message || '';
        return false;
      }
    },
    // 密码强度检查
    pwdStrengthWatch(val) {
      const reg1 = /^[a-z0-9]{6,20}$/;
      if (val && val.length >= 6) {
        if (!reg1.test(val)) {
          this.level = 3;
        } else {
          this.level = 2;
        }
      } else {
        this.level = 0;
      }
    },
    // 重置校验规则
    resetForm(formName) {
      const oldPhone = this.loginFrom.phone;
      this.$refs[formName].resetFields();
      if (formName === 'loginFrom') {
        this.loginFrom.phone = oldPhone;
      }
    },
    // 快捷登录扫码返回
    quickLoginBack() {
      this.showQrCode = false;
    },
    // 获取用户名下公司
    async getUserList(phone, password) {
      const params = {
        userCode: phone,
      };
      if (password) {
        params.password = password;
      }
      const userRes = await fetchSearchUserCode(params);
      if (userRes.success) {
        this.companyList = userRes.obj;
      } else {
        this.companyList = [];
      }
      return userRes;
    },
    // 获取行业
    async getIndustry() {
      const industryRes = await fetchGetIndustry({});
      for (const item of industryRes.obj) {
        this.industryList.push({
          text: item.DICTIONARYITEM_ITEMNAME,
          value: item.DICTIONARYITEM_ITEMCODE,
        });
      }
    },
    // 选中公司登录
    async selComapnyLogin(item, type, form) {
      /* if (this.appInfo.code && type !== 'enterCompany') {  //进入三方登录
        params.USERID = item.USERID; // edit by qinyonglian 扫码登录
        params = this.appInfo
        params.j_dept = item.DEPTID || 'default'
      } else {
        // 进入手机短信登录
        if (form.validateCode) {
          params = {
            dsfCode: form.phone,
            phonemumber: form.phone,
            loginType: 'PHONE',
            j_code: form.validateCode
            // j_dept: item.DEPTID || 'default'
          }
          params.j_dept = item.DEPTID || 'default'
        } else {
          //进入账号密码登录
          params = {
            j_username: form.phone,
            j_password: form.pwd,
            j_dept: item.DEPTID || 'default'
          }
        }
      } */

      let params = {
        checkStateId: item.CHECKID,
        proxyId: item.PROXYID,
        userId: item.USERID,
      };

      // 如果路径有casParams单点登录 参数，则合并参数
      if (this.casParams.client_id && this.casParams.response_type && this.casParams.redirect_uri) {
        params = Object.assign(params, this.casParams);
      }

      const res = await checkingUser(params);
      if (res.success) {
        if (form.phone) {
          Cookies.set('phone', form.phone, {
            expires: 30,
          });
        }
        Cookies.set('authorization', res.obj, {
          expires: 365,
        });
        // 单点登录
        if (res.code === '302') {
          window.location.href = res.obj;
        } else {
          window.location.href = '/index.html';
        }
      } else {
        this[this.formErrorMsg('loginFrom')] = res.message || res.msg;
        // this.messageTip(res.message || res.msg)
      }
    },
    // 如果用户只有一个直接登录
    async directLogin(phone, type, params) {
      let userRes;
      if (type === 'pwd') {
        userRes = await this.getUserList(phone, params.password);
      } else {
        userRes = await this.getUserList(phone);
      }
      if (userRes.success) {
        if (type === 'app') {
          this.isLoaded = true;
        }
        const companyList = userRes.obj;
        if (companyList.length > 0 && companyList.length <= 1) {
          const obj = companyList[0];
          let tempParams;
          if (type === 'code') {
            tempParams = {
              dsfCode: phone,
              phonemumber: phone,
              loginType: 'PHONE',
              j_code: params.j_code,
            };
          }
          if (type === 'pwd') {
            tempParams = {
              j_username: phone,
              j_password: params.password,
            };
          }
          if (type === 'app') {
            tempParams = params;
          }
          tempParams.j_dept = obj.DEPTID || 'default';
          this.sendLogin(tempParams);
        } else {
          this.login = false;
          this.showCompany = true;
          if (userRes.type == '0') {
            this.showSelectType = false;
          } else {
            this.showSelectType = true;
          }
        }
      } else {
        if (type === 'app') {
          this.isLoaded = true;
        }
        this[this.formErrorMsg('loginFrom')] = userRes.msg || userRes.message;
        // this.messageTip(userRes.msg || userRes.message)
      }
    },

    // 发送登录
    async sendLogin(type, params) {
      // params.expiration = this.remberStatus ? '1' : '0';
      // params.clientType = 'PC';
      let param = {};
      if (type === 'code') {
        param = {
          j_username: params.j_username,
          loginType: 'PHONE',
          j_code: params.j_code,
          state: params.state,
          isNew: 1,
        };
      } else if (type === 'pwd') {
        param = {
          j_username: params.j_username,
          j_password: params.j_password,
          code: params.j_code,
          isNew: 1,
        };
      } else if (type === 'dsf') {
        param = params;
      }

      // 如果路径有casParams单点登录 参数，则合并参数
      if (this.casParams.client_id && this.casParams.response_type && this.casParams.redirect_uri) {
        param = Object.assign(param, this.casParams);
      }

      const res = await fetchLogin(param);
      if (res.success) {
        if (params.j_username && this.remberStatus) {
          Cookies.set('phone', params.j_username, {
            expires: 30,
          });
          Cookies.set('password', param.p, {
            expires: 30,
          });
        } else {
          this.clearCookie('__jeplus_info__');
          this.clearCookie('__qc_wId');
          this.clearCookie('authorization');// 删除cookie值
          this.clearCookie('pgv_pvid');
          this.clearCookie('phone');
          this.clearCookie('password');
        }
        if (res.code === 'OK') {
          Cookies.set('authorization', res.obj, {
            expires: 365,
          });
          window.location.href = '/index.html';
        }
        // 单点登录
        if (res.code === '302') {
          window.location.href = res.obj;
        }
        if (res.code === 'CHECK') {
          /* Cookies.set('authorization', res.obj, {
            expires: 365
          }); */
          // location.href = '/index.html';
          this.companyList = JSON.parse(res.obj);
          this.login = false;
          this.showCompany = true;
          if (res.type == '0') {
            this.showSelectType = false;
          } else {
            this.showSelectType = true;
          }
        }
      } else {
        // 滑动解锁 赋予新的code值
        if (res.code == 'WARNCODE') {
          this.dragVerifycode = res.obj;
          this.dragVerifyinput = true;
          // this[this.formErrorMsg('loginFrom')] = '';
        } else if (res.code == 'NOTCERTIFIED') {
          this.login = true;
          this.loginType = true;
          this.showSelectType = false;
          this.showCompany = false;
          this.findPwd = false;
          this.updateSuccess = false;
          this.register = false;
          this.isLoaded = true;
          if (this.lang == 'zh_CN') {
            return this.$notify({
              title: '提示',
              message: '第三方认证失败，请先账号密码登录进行认证！',
              duration: 0,
            });
          }
          return this.$notify({
            title: 'prompt',
            message: 'Third party authentication failed, please login with password to authenticate！',
            duration: 0,
          });
        }
        // this[this.formErrorMsg('loginFrom')] = res.message || res.msg;
        this[this.formErrorMsg('loginFrom')] = this.utilErrorMsg(res.errorCode, res.message);
        // this.$message(res.message || res.msg);
        // this.messageTip(res.message || res.msg)
      }
    },
    // 处理返回errormsg的中英文
    utilErrorMsg(c, message) {
      const code = c.split('*')[0];
      if (!loginErrMsg[code]) return message;
      if (['1001', '1002'].indexOf(code) > -1) {
        const count = c.split('*')[1];
        const cn = loginErrMsg[code].cn1 + count + loginErrMsg[code].cn2;
        const en = loginErrMsg[code].en1 + count + loginErrMsg[code].en2;
        return this.lang == 'zh_CN' ? cn : en;
      }
      return this.lang == 'zh_CN' ? loginErrMsg[code].cn : loginErrMsg[code].en;
    },
    // 背景图片
    loadedImg() {
      let count = 10;
      const timeClear = setInterval(() => {
        count--;
        if (count <= 0) {
          clearInterval(timeClear);
          this.showImg = true;
        }
        this.filterBlur = `blur(${count}px)`;
      }, 50);
    },
    // 快捷登录
    async otherLogin(type) {
      window.loginVue = this;
      this.showQrCode = true;
      this.dsfState = await this.getState(type);

      switch (type) {
        case 'DT':
          this.typeText = '钉钉';
          dingTalkLogin({
            LOGIN_DINGTALK_APPID: this.LOGIN_DINGTALK_APPID,
            LOGIN_DINGTALK_REDIRECT_URI: this.LOGIN_DINGTALK_REDIRECT_URI,
          }, 'qr_container', this.dsfState);
          break;
        case 'WX':
          this.typeText = '微信';
          weChatLogin({
            LOGIN_WX_APPID: this.LOGIN_WX_APPID,
            LOGIN_WX_REDIRECT_URI: this.LOGIN_WX_REDIRECT_URI,
          }, 'qr_container', this.dsfState);
          break;
        case 'QQ':
          this.showQrCode = false;
          window.open(`https://graph.qq.com/oauth2.0/show?which=Login&display=pc&client_id=${this.LOGIN_QQ_APPID}&response_type=token&scope=all&redirect_uri=${this.LOGIN_QQ_REDIRECT_URI}&state=${this.dsfState}`, '_self');
          /* QC.Login.showPopup({
            appId: QQ_APPID,
            redirectURI: `${QQ_REDIRECT_URI}&state=${this.dsfState}`,
            state: this.dsfState,
          });
          console.log(QC.Login.check());
          if (QC.Login.check()) {
            QC.Login.getMe((openId, accessToken) => {
              console.log('accessToken', accessToken);
              window.qqAccessToken = accessToken;
              const qqurl = `https://graph.qq.com/oauth2.0/me?access_token=${accessToken}&unionid=1`;

              const fetchJsonp = function (url) {
                const body = document.getElementsByTagName('body')[0];
                // 插入一个script
                const script = document.createElement('script');
                script.setAttribute('src', url);
                body.appendChild(script);
              };

              // 插入一个script
              const script1 = document.createElement('script');
              script1.innerHTML = `function callback(data){window.loginVue.getOtherAppLogin({
                id: 'qq',
                authResult: {
                  access_token: window.qqAccessToken,
                  state:window.loginVue.dsfState,
                  unionId: data.unionid
                }
              })}`;
              document.body.appendChild(script1);
              // 调用
              fetchJsonp(qqurl);
            });
          } else {
            if (this.lang == 'zh_CN') {
              return this.$notify({
                title: '提示',
                message: '第三方认证失败，请先账号密码登录进行认证！',
                duration: 0,
              });
            }
            return this.$notify({
              title: 'prompt',
              message: 'Third party authentication failed, please login with password to authenticate！',
              duration: 0,
            });
          } */
          break;
        case 'SB':
          this.typeText = '轻云蒜瓣';
          this.setQRcode(this.dsfState);
          break;
      }
    },
    /**
     * 获取状态码
     */
    async getState(type) {
      try {
        const stateLogin = await fetchState({ loginType: type, type: 'PC' });
        if (stateLogin.success) {
          return stateLogin.obj.STATE;
        }
        return '';
      } catch (e) {
        return `${type}_${new Date().getTime()}`;
      }
    },
    // 获取第三方登录用户信息
    async getAppUserInfo(type) {
      const that = this;
      try {
        let res;
        if (type === 'dt') {
          res = await getDingTalkUserInfo({
            LOGIN_DINGTALK_APP_SECRET: that.LOGIN_DINGTALK_APP_SECRET,
            LOGIN_DINGTALK_APPID: that.LOGIN_DINGTALK_APPID,
          });
        } else {
          res = await getWeChatUserInfo({
            LOGIN_WX_APPID: that.LOGIN_WX_APPID,
            LOGIN_WX_SECRET: that.LOGIN_WX_SECRET,
          });
        }
        this.getOtherAppLogin({
          id: type,
          authResult: {
            openid: res.unionid,
            access_token: res.access_token,
          },
        });
      } catch (err) {
        this.isLoaded = true;
      }
    },
    // 获取其他app是否注册
    getOtherAppLogin(res) {
      if (res.authResult) {
        const state = getParam(window.location.href, 'state');
        // 是否绑定
        // const loginRes = await fetchCreateState({
        //   type: 'APP',
        //   loginType: res.id.toUpperCase(),
        //   loginCode: res.authResult.openid,
        //   access_token: res.authResult.access_token,
        //   state: state
        // })
        this.sendLogin('dsf', {
          isNew: '1',
          state: state || res.authResult.state,
          code: res.authResult.openid,
          cid: '', // 不传
          apkId: '', // 不传
          aokKey: '', // 不传
          token: '', // 不传
          type: '',
        });
        // if (loginRes.success) {
        //   if (loginRes.obj.data.length > 0) {
        //     this.appInfo = {
        //       code: res.authResult.openid,
        //       access_token: res.authResult.access_token,
        //       state: this.dsfState,
        //       loginType: res.id.toUpperCase(),
        //       DEPTID: loginRes.DEPTID,
        //       phone: loginRes.phone,
        //     }
        //     this.directThreeLogin(this.appInfo)
        //   } else {
        //     this.isLoaded = true
        //     this.appInfo = {
        //       code: res.authResult.openid,
        //       type: res.id.toUpperCase(),
        //       openId: res.authResult.openid,
        //       accessToken: res.authResult.access_token,
        //       state: state
        //     }
        //     this.goRegister(res.id.toUpperCase())
        //   }
        // } else {
        //   this.isLoaded = true
        // }
      } else {
        this.isLoaded = true;
      }
    },
    // 从第三方扫码之后处理逻辑
    async directThreeLogin(params) {
      /* if (companyList.length > 0 && companyList.length <= 1) {
        const obj = companyList[0] */
      const tempParams = {
        loginType: params.loginType,
        // j_username: obj.phone,
        j_username: params.phone,
        code: params.code,
        state: params.state,
        isNew: 1,
        // deptId: obj.DEPTID || 'default'
        deptId: params.DEPTID || 'default',
      };
      this.sendLogin('dsf', tempParams);
      /* } else if (companyList.length <= 0) {
        JE.message_msg('该认证方式没有绑定，请使用手机登录哈~')
        location.href = '/index.html'

      } else {
        this.login = false
        this.showCompany = true
      } */
    },
    // 注册跳转
    goRegister(type) {
      this.register = true;
      this.login = false;
      this.isShowRegister = '1';
      this.registerFrom3 = {};
      this.registerForm3ErrorMsg = '';
      this.registerFromErrorMsg = '';
      this.registerFrom = {};
      this.registerSuccess = {};
      this.sendAuthCode = true;
      this.auth_time = 0;
      this.resetForm('registerFrom');
      this.resetForm('registerFrom3');
      this.getIndustry();
      this.registerType = type;
    },
    // 蒜瓣二维码登录
    async setQRcode(state) {
      const qrText = generateQRcode('qr_container');
      document.getElementById('qr_container').style.paddingTop = '30px';
      const qrcode = await fetchSetQRcode({
        code: qrText,
        state,
      });
      if (qrcode.success) {
        const qrInterval = setInterval(async () => {
          const res = await fetchQRlogin({
            code: qrText,
            token: 1,
          });
          if (res.success) {
            if (res.obj) {
              clearInterval(qrInterval);
              /* this.directLogin(res.obj.phone, 'code', {
                j_code: res.obj.j_code
              }) */
              Cookies.set('authorization', res.obj.token);
              location.href = '/index.html';
            }
          } else {
            clearInterval(qrInterval);
            // this.messageTip('二维码失效，请重新扫描')
            this.setQRcode();
          }
        }, 3000);
      }
    },
    messageTip(msg, type = 'warning') {
      // Message[type]({
      //   showClose: true,
      //   message: msg || ''
      // })
    },
    getEn(cn) {
      if (!cn) return;
      if (this.lang == 'zh_CN') return cn;
      return spe[cn] || cn;
    },
  },
};
